package com.financing.platform.web.api;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.FaUserDTO;
import com.financing.platform.dto.FaUserVisitDTO;
import com.financing.platform.service.IFaUserService;
import com.financing.platform.service.IFaUserVisitService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.Dict;
import com.financing.platform.util.StringUtil;

@Controller("faUserVisitActionApi")
@RequestMapping("/api/fa")
@Scope("prototype")
public class FAUserVisitAction extends BaseAction {

	@Autowired
	private IFaUserVisitService faUserVisitServiceImpl;

	@Autowired
	private IFaUserService faUserServiceImpl;

	@RequestMapping("/queryFaUserVisit.shtml")
	@ResponseBody
	public ResultMap queryFaUserVisit(HttpServletRequest request, HttpServletResponse response, FaUserVisitDTO faUserVisitDTO, String loginName) {
		try {
			log.info("Begin queryFaUserVisit!");
			// 判断是loginName 还是FAID
			if(!StringUtil.isNullOrEmptyStr(loginName)){
				// 查出FAID
				faUserVisitDTO.setFaId(faUserVisitServiceImpl.queryFaIdByLoginName(loginName));
//				faUserVisitDTO.setType("3");//【用户行为】备注type
			}
			List<FaUserVisitDTO> faUserVisitList = faUserVisitServiceImpl.queryFaUserVisit(faUserVisitDTO);

			resultMap.setAttribute("list", faUserVisitList);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);

			log.info("End queryFaUserVisit!");
		} catch (Exception e) {
			log.error("queryFaUserVisit error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}

	@RequestMapping("/addFaUserVisit.shtml")
	@ResponseBody
	public ResultMap addFaUserVisit(HttpServletRequest request, HttpServletResponse response, FaUserVisitDTO faUserVisitDTO, String loginName) {

		DTOdateSet.setCreateInfo(faUserVisitDTO, request.getSession());
		DTOdateSet.setUpdateInfo(faUserVisitDTO, request.getSession());
		faUserVisitDTO.setVisitPerson(faUserVisitDTO.getCreateBy());
		try {
			// 判断是loginName 还是FAID
			if(!StringUtil.isNullOrEmptyStr(loginName)){
				// 查出FAID
				faUserVisitDTO.setFaId(faUserVisitServiceImpl.queryFaIdByLoginName(loginName));
				faUserVisitDTO.setType("3");//【用户行为】备注type
			}
			faUserVisitServiceImpl.addFaUserVisit(faUserVisitDTO);
			// 更新最后回访时间
			faUserVisitServiceImpl.updateLastVisitTime(faUserVisitDTO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (SQLException e) {
			log.error("queryFaUserVisit error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}

	@RequestMapping("/updateADFaUser.shtml")
	@ResponseBody
	public ResultMap updateADFaUser(HttpServletRequest request, HttpServletResponse response) {
		String faId = request.getParameter("faId");
		String adValid = request.getParameter("adValid");
		FaUserDTO faUserDTO = new FaUserDTO();
		faUserDTO.setId(faId);
		faUserDTO = faUserServiceImpl.queryFaUserInfo(faUserDTO);

		log.info(faUserDTO.getMediaSource());
		// 注册来源不亿起发 (sourceCode 不为-2)则不进行任何处理
		if (!"YQF".equals(faUserDTO.getMediaSource()) || "1".equals(faUserDTO.getIsValid()) || "0".equals(faUserDTO.getIsValid())) {
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR + "isValid:" + faUserDTO.getIsValid());
			log.error("fa source Code error!");
			return resultMap;
		}

		if (faUserDTO.getIsValid() == null || faUserDTO.getIsValid().equals(Dict.isValid_unknown)) {
			faUserDTO.setIsValid(adValid);
		}
		DTOdateSet.setUpdateInfo(faUserDTO, request.getSession());
		try {
			faUserServiceImpl.updateFaUserADInfo(faUserDTO);
		} catch (SQLException e) {
			log.error("update fa user info error!", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}

		// 有效性校验通过 通知亿起发
		if (adValid.equals(Dict.isValid_pass)) {
			URL url = null;
			try {
				url = new URL("http://o.yiqifa.com/servlet/handleCpaIn?cid=17987&wi=" + faUserDTO.getRemark() + "&ana=reg&an="
						+ faUserDTO.getId() + "&ct=basic&ta=1&sd=" + URLEncoder.encode(StringUtil.dateNowStr("yyyy-MM-dd HH:mm:ss")));
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.connect();
				InputStream in = connection.getInputStream();
				BufferedReader breader = new BufferedReader(new InputStreamReader(in, "GBK"));
				log.info("url response is" + breader.readLine());
			} catch (Exception e1) {
				log.error("request url" + url + "error", e1);
			}
		}

		resultMap.setStatus(STATUS.SUCCESS);
		resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		return resultMap;
	}

	public static void main(String[] args) throws Exception {
		// URL url = new
		// URL("http://o.yiqifa.com/servlet/handleCpaIn?cid=tset");
		URL url = new URL("http://o.yiqifa.com/servlet/handleCpaIn?cid=17987&wi=" + "ws" + "&ana=reg&an=" + "fdsa" + "&ct=basic&ta=1&sd="
				+ URLEncoder.encode(StringUtil.dateNowStr("yyyy-MM-dd HH:mm:ss")));
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.connect();
		InputStream in = connection.getInputStream();
		java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in, "GBK"));
		String str = breader.readLine();
		while (str != null) {
			System.out.println(str);
			str = breader.readLine();
		}
	}
}
